package lhc.learn.nio;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Lihc on 2016/3/24.
 */
public class TimeClientHandler implements Runnable {
    /**
     * 主机
     */
    private String host = "127.0.0.1";
    /**
     * 端口
     */
    private int port = 8080;
    /**
     * 轮询器
     */
    private Selector selector;

    /**
     * 管道
     */
    private SocketChannel channel;

    private volatile boolean stop;

    public TimeClientHandler() {
        try {
            selector = Selector.open();
            channel = SocketChannel.open();
            channel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
        }
    }

    /**
     * 线程方法
     */
    @Override
    public void run() {
        try {
            if (channel.connect(new InetSocketAddress(host, port))) {
                handle(channel);
            } else {
                channel.register(selector, SelectionKey.OP_CONNECT);
            }
            SelectionKey selectionKey = null;
            while (!stop) {
                System.out.println(selector.select(1000));
                Set<SelectionKey> set = selector.selectedKeys();
                Iterator<SelectionKey> iterator = set.iterator();
                while (iterator.hasNext()) {
                    selectionKey = iterator.next();
                    iterator.remove();
                    if (!selectionKey.isValid()) {
                        continue;
                    }
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    if (selectionKey.isWritable()) {
                        System.out.println("write");
                    }
                    if (selectionKey.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int num = socketChannel.read(buffer);
                        if (num > 0) {
                            buffer.flip();
                            byte[] arr = new byte[buffer.remaining()];
                            buffer.get(arr);
                            System.out.println("the result is :" + new String(arr, "UTF-8"));
                        } else if (num < 0) {
                            selectionKey.cancel();
                            IOUtils.closeQuietly(socketChannel);
                        }
                        this.stop = true;
                    }
                    if (selectionKey.isConnectable()) {
                        //判断连接是否结束
                        if (socketChannel.finishConnect()) {
                            handle(socketChannel);
                        } else {
                            System.exit(1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
        }
    }

    private void handle(SocketChannel socketChannel) throws Exception {
        socketChannel.register(selector, SelectionKey.OP_READ);
        byte[] req = "time".getBytes("UTF-8");
        ByteBuffer buffer = ByteBuffer.allocate(req.length).put(req);
        buffer.flip();
        socketChannel.write(buffer);
        if (!buffer.hasRemaining()) {
            System.out.println("send end");
        }
    }
}
